#!/usr/bin/env python
#Vort Rider: Riding the Vorterix the good way
#CLI interface

import subprocess
import sys

import vortrider

def get_settings():
    settings = {'video_player': 'mplayer',
                'audio_player': 'mplayer',
               }
    return settings

def show_menu(items):
    "Allows the user to choose an option from items"
    for i, item in enumerate(items):
        print ':%02d: %s' % (i, item)
    resp = raw_input('Select an option: ')
    if resp.isdigit():
        resp = int(resp)
    return resp


def play_video(video_url):
    "Runs the video player"
    settings = get_settings()
    print 'Playing (%s)...' % video_url
    return subprocess.call([settings['video_player'], video_url])


def play_audio(audio_url):
    "Runs the audio player"
    settings = get_settings()
    print 'Playing audio from (%s)...' % audio_url
    return subprocess.call([settings['audio_player'], audio_url])


def show_videos_def(rawdata):
    data = vortrider.parse_videos_def(rawdata)
    option = show_menu([x['titulo'] for x in data['items']])
    if option in range(len(data['items'])):
        video_data = vortrider.get_video_data(data['items'][option]['urlXML']) 
        play_video(video_data['url_alta'])
    return option


def show_publicidadades(rawdata):
    data = vortrider.parse_publicidades(rawdata)
    option = show_menu([x['nombre'] for x in data['items']])
    if option in range(len(data['items'])):
        play_video(data['items'][option]['url_alta'])
    return option


def show_destacados(rawdata):
    data = vortrider.parse_destacados(rawdata)
    option = show_menu(['%s - %s' % (x['texto'], x['subtexto']) for x in data['items']])
    if option in range(len(data['items'])):
        play_audio(data['items'][option]['url_audio'])
    return option


def show_napolitano(rawdata):
    data = vortrider.parse_napolitano(rawdata)
    option = show_menu(['%s - %s' % (x['song'], x['artist']) for x in data['items']])
    if option in range(len(data['items'])):
        play_video(data['items'][option]['url'])
    return option


def show_section(sec_name, sec_rawdata):
    sec_map = {
               'publicidades': show_publicidadades,
               'videos_az': show_videos_def,
               'videos_date': show_videos_def,
               'videos_def': show_videos_def,
               'destacados': show_destacados,
               'napolitano': show_napolitano,
               }
    exit = False
    while not exit:
        option = sec_map[sec_name](sec_rawdata)
        exit = option == 'q'


def __main__(argv=None):
    if argv is None:
        argv = sys.argv
    print '-.- Vort Rider -.-'
    print 'Getting main sections...'
    sections = vortrider.get_main_sections()
    section = show_menu([x[0] for x in sections])
    if section != 'q':
        show_section(*sections[section])
    else:
        print 'Bye!'


if __name__ == '__main__':
    sys.exit(__main__())
